<template>
  <div class="mine bg-hex-fff">
    <div class="sticky left-0 right-0 top-0 z-999 h-full px-28rpx">
      <trn-nav v-if="scroll_value > top_nav_height" :propScroll="scroll_value" :propHeight="top_nav_height">
        <div class="absolute top-0 z-99999 flex items-center px-20rpx" :style="{ paddingTop: `${searchBarTop}px` }"
             @click.stop="goback">
          <uni-icons type="back" size="28" />
          <text class="text-36rpx font-600">返回</text>
        </div>
      </trn-nav>
    </div>
    <div class="relative left-0 right-0 top-0 z-99 h-full">
      <div class="relative box-border" :style="{ paddingTop: `${searchBarTop}px` }">
        <image class="pointer-events-none absolute left-0 right-0 top-0 z--9 h-470rpx w-100% overflow-hidden"
               :src="`${cdnUrl}/imgs/mine/bg.png${imgVersion}`" mode="aspectFill" />
        <div v-if="scroll_value < top_nav_height" class="flex items-center pb-40rpx pl-16rpx" @click.stop="goback">
          <uni-icons type="back" size="28" />
          <text class="text-36rpx font-600">返回</text>
        </div>
        <div class="box-border p-30rpx pt-0rpx">
          <div>
            <div class="flex items-center justify-between">
              <div class="mb-18rpx flex items-center">
                <div>
                  <image class="mr-24rpx h-80rpx w-80rpx rounded-100%" :src="userStore.infoData.avatar_url"
                         mode="scaleToFill" />
                </div>
                <div class="flex items-center">
                  <div class="mr-20rpx text-28rpx font-600 text-hex-333333">{{ userStore.infoData.nickname }}</div>
                  <div v-if="userStores.user.verified===1">
                    <div
                      class="h-32rpx w-32rpx flex items-center justify-center rounded-50% bg-hex-FFA522 text-26rpx text-hex-FFFFFF">√</div>
                    <span class="ml-12rpx text-26rpx !text-hex-ABCD03">已认证</span>
                  </div>
                  <div v-else class="ml-12rpx text-26rpx !text-hex-ABCD03" @click="handleApplication">申请达人认证</div>
                </div>
              </div>
              <!-- <div v-if="Number(userId)===Number(userStore.user?.id)" class="flex items-center justify-between" @tap="openShare">
                <image class="h-56rpx w-56rpx" :src="`${cdnUrl}/svgicons/pl_share.svg${imgVersion}`" mode="scaleToFill" />
              </div> -->
            </div>
            <span class="mb-20rpx ml-18rpx w-64% text-24rpx leading-5 text-hex-5A736A">{{ tags }}</span>
            <div class="mb-20rpx ml-18rpx w-64% text-24rpx leading-5 text-hex-5A736A">{{ userStore.infoData.remark??'暂无简介'
            }}</div>
            
            <div class="relative">
              <!-- <image class="absolute left-0 right-0 top-0 z--9 h-146rpx w-100%" :src="`${cdnUrl}/imgs/mine/bg1.png${imgVersion}`" /> -->
              <div class="z-9999 box-border flex items-center justify-around py-40rpx pt-10rpx">
                <div class="flex flex-col items-center"
                     @click="routerTo(`/pages-mine/trends?userId=${userStore.infoData.id}`)">
                  <div class="text-28rpx font-bold text-hex-333">{{ userStore.conuts.trendsCount ?? 0 }}</div>
                  <div class="text-24rpx text-hex-333">全部</div>
                </div>
                <div class="flex flex-col items-center"
                     @click.stop="routerTo(`/pages-mine/fans?userId=${userStore.infoData.id}`)">
                  <div class="text-28rpx font-bold text-hex-333">{{ userStore.conuts.fansCount ?? 0 }}</div>
                  <div class="text-24rpx text-hex-333">粉丝</div>
                </div>
                <div class="flex flex-col items-center"
                     @click.stop="routerTo(`/pages-mine/attentions?userId=${userStore.infoData.id}`)">
                  <div class="text-28rpx font-bold text-hex-333">{{ userStore.conuts.attentionCount ?? 0 }}</div>
                  <div class="text-24rpx text-hex-333">关注</div>
                </div>
                <!-- 判断是否可编辑 -->
                <div v-if="Number(userId)===Number(userStore?.user.id)" class="flex">
                  <div
                    class="h-52rpx w-148rpx flex items-center justify-center border-2rpx border-hex-333 rounded-68rpx border-solid bg-hex-fff text-24rpx text-hex-333"
                    @click="navTo('/pages-mine/personInfoEdit')">
                    编辑资料
                  </div>
                  <div class="ml-32rpx flex items-center justify-between" @tap="openShare">
                    <image class="h-56rpx w-56rpx" :src="`${cdnUrl}/svgicons/pl_share1.svg${imgVersion}`"
                           mode="scaleToFill" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="mx-32rpx rounded-t-32rpx pb-100rpx">
      <div ref="targetElement" class="target-element z-999 box-border h-100rpx bg-hex-fff"
           :style="scroll_value>=targetTop ? `position: sticky;left:0;right:0;top:${searchBarTop+barHeight-13}px` : ''">
        <div class="flex justify-around">
          <div v-for="item in tabList" class="flex flex-col justify-center text-28rpx text-hex-666666"
               @click="changetabindex(item.index)">
            <text class="z-9" :class="{ 'text-32rpx text-hex-383B34 font-600': tabindex === item.index }">{{ item.text
            }}</text>
            <image v-if="tabindex===item.index" class="relative z-99 h-30rpx w-64rpx -mt-10rpx"
                   :src="`${cdnUrl}/imgs/square/selected.png${imgVersion}`" mode="scaleToFill" />
          </div>
        </div>
      </div>
      <s-waterfall v-if="waterfallList.length>0" :datalist="waterfallList" :column="2">
        <template #default="{ item }">
          <div class="mb-24rpx box-border rounded-32rpx pr-32rpx"
               @click="navTo(`/pages-square/articledetail?articleId=${item.id}`)">
            <div
              class="bg-water relative mb-24rpx max-h-500rpx w-326rpx flex items-center justify-center overflow-hidden rounded-32rpx bg-hex-FAF9F8">
              <image class="h-100% w-100% rounded-24rpx" lazy-load :src="item.imgUrl" mode="widthFix" />
              <div v-if="item.articleType===2" class="absolute right-30rpx top-45rpx flex items-center justify-center">
                <image :src="`${cdnUrl}/imgs/square/radio.png${imgVersion}`" mode="widthFix" class="w-60rpx" />
              </div>
            </div>
            <text class="multiLine-hiddle mx-10rpx mt-10rpx inline-block font-600">{{ item.title }}</text>
            <div class="mb-22rpx mr-15rpx box-border flex items-center justify-between">
              <div class="flex items-center">
                <image class="mr-15rpx h-44rpx w-44rpx rounded-50%" :src="item.avatar_url" mode="scaleToFill" />
                <text class="text-24rpx text-hex-7C8699">{{ item.nickname }}</text>
              </div>
              <div v-if="isMyself" class="flex justify-center text-right text-hex-ABAFB5"
                   @click.stop="opendelpop(item.id)">
                <image class="w-46rpx" :src="`${cdnUrl}/svgicons/del.svg${imgVersion}`" mode="widthFix" />
              </div>
            </div>

            <div v-show="currPoint === item.id && isShowPoint" class="relative">
              <div
                class="absolute bottom-80rpx left-0 box-border h-66rpx w-336rpx flex items-center justify-between rounded-lg bg-hex-fff px-16rpx text-hex-333"
                style="box-shadow: 0 4px 20px 0 rgb(0 0 0 / 5%);">
                <image class="h-44rpx w-44rpx" :src="`${cdnUrl}/svgicons/pl_like${isLike}.svg${imgVersion}`" alt=""
                       mode="scaleToFill" @click.stop="handleClickLike1(item)" />
                <image class="h-44rpx w-44rpx" :src="`${cdnUrl}/svgicons/pl_save${isCollect}.svg${imgVersion}`" alt=""
                       mode="scaleToFill" @click.stop="handleClickCollect1(item)" />
                <image class="h-44rpx w-44rpx" :src="`${cdnUrl}/svgicons/pl_msg.svg${imgVersion}`" mode="scalitemeToFill"
                       alt="" @click.stop="routerTo(`/pages-square/articledetail?articleId=${item.id}`)" />
                <image class="h-44rpx w-44rpx" :src="`${cdnUrl}/svgicons/pl_share.svg${imgVersion}`" mode="scaleToFill"
                       alt="" @click.stop="open" />
              </div>
            </div>
          </div>
        </template>
      </s-waterfall>
      <div v-else class="flex items-center justify-center">
        <div>
          <image class="h-264rpx w-264rpx" :src="`${cdnUrl1}/imgs/xy/other/noneeattention.png${imgVersion}`"
                 mode="scaleToFill" />
          <div class="text-center text-28rpx text-hex-7C8699">暂无数据</div>
        </div>
      </div>
    </div>
    <uni-popup ref="popup" type="bottom" background-color="#fff" class="z-999">
      <go-share class="z-99999" @close="closepop" />
    </uni-popup>
    <div v-if="isShowShare" class="absolute top-0 z-999 h-full w-full bg-[rgba(0,0,0,0.7)]">
      <owner-share :user-info="userStore.infoData" @close="closeShare" />
    </div>
    <!-- 删除弹窗 -->
    <confirm ref="delpop" />
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores/user'

const loginStore = useLoginStore()
const userStores = useUserStore()

//顶部导航
let scroll_value = $ref(0)
let top_nav_height = $ref(50)

let targetElement = $ref()
let targetTop = $ref(0)
let searchBarTop: any = $ref('24')
let barHeight = $ref(0)
let userId = $ref()
let tags: any = $ref('')
onLoad((options: any) => {
  if (options.scene) {
    userId = options.scene
    return
  }
  userId = options.userId
  const systemInfo = uni.getSystemInfoSync()
  const statusBarHeight: any = systemInfo.statusBarHeight // 状态栏高度
  barHeight = statusBarHeight
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  // #endif
})
onPageScroll((e) => {
  scroll_value = e.scrollTop
})
const userStore = useUserStore()

let myId = (userStore.user.id).toString()
const isMyself = $computed(() => {
  return userId === myId
})
let tabindex = $ref('')

let currPoint = $ref(0)
let isShowPoint = $ref(true)
let isLike = $ref(false) //是否点赞
let isCollect = $ref(false) //是否收藏
const handleClickMore = (item) => {
  if (currPoint === item.id) {
    isShowPoint = false
    currPoint = 0
    return
  }
  isShowPoint = true
  currPoint = item.id
  getSuggestMoreInfo(item)
}
const popup: any = $ref(null)
const openShare = () => {
  isShowShare = true
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 0,
  })
}
const open = () => {
  popup.open('bottom')
}
const closepop = () => {
  popup.close()
}

// 删除弹窗
const delpop: any = $ref('')
const opendelpop = (id) => {
  delpop.showConfirm('确定删除此作品吗?').then((res) => {
    if (res) {
      deleteArticle(id)
    }
  })
}
//删除文章
const deleteArticle = async (articleId) => {
  const reqData = { method: 'delete' }
  const { data, status, error } = await Fetch(`/qqyapi/auth/article/deleteArticle/${articleId}`, reqData)
  if (data.code === 0) {
    waterfallList.splice(waterfallList.findIndex(item => item.id === articleId), 1)
    uni.showToast({
      title: '删除成功',
      duration: 1500,
    })
  }
}
//推荐列表：收藏,取消收藏
const handleClickCollect1 = async (item) => {
  const reqData = {
    method: 'post',
    data: {
      'articleId': item.id,
    },
  }
  switch (isCollect) {
    case false:
      await Fetch('/qqyapi/auth/collect/addCollect', reqData).then(res => {
        if (res.status === 200 && res.data.code === 0) {
          getSuggestMoreInfo(item)
        }
      })
      break
    case true:
      await Fetch('/qqyapi/auth/collect/cancelCollect', reqData).then(res => {
        if (res.status === 200 && res.data.code === 0) {
          getSuggestMoreInfo(item)
        }
      })
      break
  }
}
//推荐列表：点赞,取消点赞
const handleClickLike1 = async (item) => {
  const reqData = {
    method: 'post',
    data: {
      'articleId': item.id,
    },
  }
  switch (isLike) {
    case false:
      await Fetch('/qqyapi/auth/article/like/addLike', reqData).then(res => {
        if (res.status === 200 && res.data.code === 0) {
          getSuggestMoreInfo(item)
        }
      })
      break
    case true:
      await Fetch('/qqyapi/auth/article/like/cancelLike', reqData).then(res => {
        if (res.status === 200 && res.data.code === 0) {
          getSuggestMoreInfo(item)
        }
      })
      break
  }
}
const getSuggestMoreInfo = async (item) => {
  const reqData = {
    method: 'get',
    data: {
      articleId: item.id,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/auth/article/indexArticleStat', reqData)
  isLike = Boolean(data.result.isLike)
  isCollect = Boolean(data.result.isCollect)

}
const tabList = [
  { index: '', text: '最近' },
  { index: '1', text: '文章' },
  { index: '2', text: '视频' },
  { index: '0', text: '动态' },
]

const changetabindex = (index) => {
  tabindex = index
}
const routerTo = (route) => {
  uni.navigateTo({
    url: route,
  })
}
const goback = () => {
  uni.navigateBack({
    delta: 1,
  })
}
const goodsList = [
  { imgUrl: `${cdnUrl}/imgs/square/test1.png${imgVersion}` },
  { imgUrl: `${cdnUrl}/imgs/square/test2.png${imgVersion}` },
  { imgUrl: `${cdnUrl}/imgs/square/test2.png${imgVersion}` },
  { imgUrl: `${cdnUrl}/imgs/square/test2.png${imgVersion}` },
]
let isShowShare = $ref(false)
const fnApplicationApi = (options, method, msg) => {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    const { data, status } = await Fetch('/api/s/t/user_verified_application',
      { method, data: options, headers: { timestamp: Date.now() } })
    if (status === 200 && data.code === 0) {
      uni.showToast({
        title: msg,
        icon: 'none',
        duration: 2000,
      })
      resolve(data)
    } else {
      reject(data.msg)
    }
  })
}
//申请达人
const handleApplication = async () => {
  const { data, error, status } = await Fetch('/qqyapi/member/userVerifiedApplications/exist', {
    method: 'get',
  })
  if (status === 200 && data.code === 0) {
    if (!data.result) {
      fnApplicationApi({
        contact_mobile: userStores.user.mobile,
        status: 0,
        user_id: userStores.user.id,
        nickname: userStores.user.nickname,
      }, 'put', '申请成功')
    } else {
      uni.showToast({
        title: '已申请不能重复申请',
        icon: 'none',
        duration: 2000,
      })
    }
  }
}

onPageScroll(() => {
  isShowShare = false
})

const closeShare = () => {
  isShowShare = false

}
let suggestList: any = $ref([])
let waterfallList: any = $ref([])
let baseData: any = $ref([])
let suggestMore = $ref(false)
let limit = $ref(10)
let offset = $ref(1)
let totalPage = $ref()
const getSuggestList = async () => {
  const reqData = {
    method: 'get',
    data: removeEmptyFields({
      type: tabindex,
      pageNo: offset,
      pageSize: limit,
      userId,
    }),
  }
  const { data, status, error } = await Fetch('/qqyapi/auth/article/articlePageList', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (isNotNilOrEmpty(data.result.dataList)) {
    baseData = data.result.dataList
    totalPage = data.result.totalPage
    suggestList = suggestList.concat(baseData.map(e => {
      e.imgUrl = e.coverImage
      e.avatar_url = e.avatarUrl
      return e
    }))
  }
  waterfallList = clone(suggestList)
  if (suggestList.length < data.result.total) {
    suggestMore = true
    return
  }
  suggestMore = false
}

//下滑加载更多数据
const getMoreData = () => {
  //判断总页数和当前页数进行加载请求
  if (totalPage !== offset) {
    offset++
    getSuggestList()
  }
}
onReachBottom(() => {
  getMoreData()
})
watch(() => tabindex, () => {
  offset = 1
  suggestList = []
  waterfallList = []
  uni.pageScrollTo({
    scrollTop: scroll_value >= targetTop ? targetTop : 0,
    duration: 0,
  })
  getSuggestList()
})
//请求标签
const fnApi = (options, method, msg) => {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    const { data, status } = await Fetch('/api/s/t/user_label_link',
      { method, data: options, headers: { timestamp: Date.now() } })
    if (status === 200 && data.code === 0) {
      resolve(data)
    } else {
      reject(data.msg)
    }
  })
}
onMounted(async () => {
  userStore.getInfo(userId)
  const res: any = await fnApi({ user_id: userId }, 'post', null)
  tags = res.result.dataList.map(item => item.user_label_name).join('|')
  getSuggestList()
  nextTick(() => {
    uni.createSelectorQuery()
      .select('.target-element')
      .boundingClientRect((rect: any) => {
        if (rect) {
          // 计算元素距离胶囊的位置
          const distanceToCapsule = rect.top - barHeight - searchBarTop
          targetTop = distanceToCapsule
        }
      })
      .exec()
  })
})
</script>

<style lang="scss" scoped>
.mine {
  .multiLine-hiddle {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-all;
  }

  .regular {
    position: sticky;
    left: 0;
  }
}
</style>
